<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-30 10:36:10
 * @LastEditors: your name
 * @LastEditTime: 2021-05-06 15:27:19
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="600px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? $t("sys.new_classification") : $t("sys.edit_classification") }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="120px">
      <el-form-item
        :label="$t('sys.classification_name')"
        prop="name"
        :rules="[
          { required: true, message: $t('sys.classification_name_not_null'), trigger: 'change' },
          { validator: nameValidator, trigger: 'change' },
        ]"
      >
        <el-input
          v-model="formData.name"
          style="width: 400px"
          :placeholder="$t('sys.enter_classification_name')"
          :maxlength="64"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="tr">
      <el-button @click="showVisible = false">{{$t('sys.cancel')}}</el-button>
      <el-button type="primary" @click="submit">{{$t('sys.confirm')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    folders: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      showVisible: false,
      formData: {},
      callback: null,
    };
  },

  computed: {
    isNew() {
      return !this.formData.id;
    },
  },

  methods: {
    open(data = {}, callback = null) {
      this.formData = {
        ...data,
      };
      this.callback = callback;
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    nameValidator(rule, value, callback) {
      if (
        this.isNew &&
        this.folders.find((folder) => folder.name === (value || "").trim())
      ) {
        callback(new Error(this.$t("sys.classification_name_exist")));
      } else {
        callback();
      }
    },

    async submit() {
      try {
        await this.$refs.form.validate();
        const { name } = this.formData;
        this.callback && this.callback(name);
        this.showVisible = false;
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
